<script lang="ts" setup>
import {
  ElButton,
  ElTabs,
  ElTabPane,
  ElRow,
  ElCol,
  ElTreeSelect,
  ElForm,
  ElFormItem,
  ElInput,
  ElIcon,
  ElDivider,
  ElUpload,
  ElDialog,
  ElTable,
  ElMessage,
} from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { router } from "#/router";
import airportList from "./airportList.vue";
import GaoAmap from "./selectMap.vue";
import { add, edit, getAirportById } from "#/api/sys/equipment";
import { getOrganizationsByUserId } from "#/api/sys/organization";
import Upload from "#/adapter/component/Upload/Upload.vue";

const disabled = ref(false);
const acceptImg = ref(".jpg,.jpeg,.png");
const isShowTip = reactive({
  isShow: false,
  message: "",
});

// 地图demo
const amapVisible = ref(false);
const defaultAddress = ref("");
const defaultPoint = ref([]);
const mapConfig = reactive({
  // defaultPoint: [116.397428, 39.90923],
  // defaultAddress: "天安门",
  defaultPoint: [],
  defaultAddress: "",
});
const isVisible = ref(true);

const activeName = ref("first");
const title = ref("添加机场");
const handleBack = () => {
  router.go(-1);
};

const ruleFormRef = ref();
const ruleForm = reactive<RuleForm>({
  id: router.currentRoute.value.query.id
    ? +router.currentRoute.value.query.id
    : "",
  organizationId: "",
  airportName: "",
  longitude: "", // 经度
  latitude: "", // 纬度
  address: "", //机场位置
  gatewaySn: "",
  description: "",
  airportImage: "",
  ipAddress: "",
  gateway: "",
  videoAddress: "",
  windSpeedThreshold: "",
  rainfallThreshold: "",
  droneIds: [],
  droneList: [],
});
const selectList = ref([]);
const dialogVisible = ref(false);

const spaceInput = (field: string, value: string) => {
  // 过滤空格
  ruleForm[field] = value.replace(/\s+/g, "");
};

const updateImg = (img) => {
  ruleForm.airportImage = img;
};

const getDetail = async (id) => {
  const params = {
    id: id,
  };
  const { data } = await getAirportById(params);
  ruleForm.organizationId = data.organizationId;
  ruleForm.airportName = data.airportName;
  ruleForm.longitude = data.longitude;
  ruleForm.latitude = data.latitude;
  ruleForm.address = data.address;
  ruleForm.gatewaySn = data.gatewaySn;
  ruleForm.description = data.description;
  ruleForm.airportImage = data.imageUrl;
  ruleForm.ipAddress = data.ipAddress;
  ruleForm.gateway = data.gateway;
  ruleForm.videoAddress = data.videoAddress;
  ruleForm.windSpeedThreshold = data.windSpeedThreshold;
  ruleForm.rainfallThreshold = data.rainfallThreshold;
  ruleForm.droneList = data.droneList;
  ruleForm.droneIds = data.droneIds;
  selectList.value = data.droneList;
  isVisible.value = false;
};

if (ruleForm.id) {
  title.value = "编辑机场";
  getDetail(router.currentRoute.value.query.id);
}
const rules = reactive({
  airportName: [
    { required: true, message: "请输入机场名称", trigger: "blur" },
    // { min: 2, max: 50, message: "请输入最多50字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 50) {
          callback(new Error("请输入最多50个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  organizationId: [
    { required: true, message: "请选择所属组织", trigger: "change" },
  ],
  // longitude: [
  //   { required: true, message: '请输入经度', trigger: 'blur' },
  //   {
  //     validator: (rule, value, callback) => {
  //       if (value && !/^-?\d{1,3}(\.\d+)?$/.test(value)) {
  //         callback(new Error('经度格式不正确(-180~180)'));
  //       } else if (
  //         value &&
  //         (parseFloat(value) < -180 || parseFloat(value) > 180)
  //       ) {
  //         callback(new Error('经度范围应在-180~180之间'));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: 'blur',
  //   },
  // ],
  // latitude: [
  //   { required: true, message: '请输入纬度', trigger: 'blur' },
  //   {
  //     validator: (rule, value, callback) => {
  //       if (value && !/^-?\d{1,2}(\.\d+)?$/.test(value)) {
  //         callback(new Error('纬度格式不正确(-90~90)'));
  //       } else if (
  //         value &&
  //         (parseFloat(value) < -90 || parseFloat(value) > 90)
  //       ) {
  //         callback(new Error('纬度范围应在-90~90之间'));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: 'blur',
  //   },
  // ],
  address: [
    { required: true, message: "请输入机场位置", trigger: "blur" },
    // { min: 2, max: 50, message: "请输入最多50字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 50) {
          callback(new Error("请输入最多50个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  gatewaySn: [
    // { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" }
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 20) {
          callback(new Error("请输入最多20个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  ipAddress: [
    { required: true, message: "请输入IP地址", trigger: "blur" },
    // { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 20) {
          callback(new Error("请输入最多20个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  gateway: [
    { required: true, message: "请输入网关", trigger: "blur" },
    // { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 20) {
          callback(new Error("请输入最多20个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  videoAddress: [
    { required: true, message: "请输入视频地址", trigger: "blur" },
    // { min: 1, max: 200, message: "请输入最多200字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 200) {
          callback(new Error("请输入最多200个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  windSpeedThreshold: [
    { required: true, message: "请输入风速阈值", trigger: "blur" },
    // { min: 1, max: 10, message: "请输入最多10字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 10) {
          callback(new Error("请输入最多10个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  rainfallThreshold: [
    { required: true, message: "请输入降雨阈值", trigger: "blur" },
    // { min: 1, max: 10, message: "请输入最多10字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 10) {
          callback(new Error("请输入最多10个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  description: [
    // { min: 1, max: 50, message: "请输入最多50字", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.length > 50) {
          callback(new Error("请输入最多50个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
const treeData = ref([]);
const defaultProps = {
  children: "children",
  label: "organizationName",
};

const selectAirport = ref("");
const bindAddUAV = () => {
  selectAirport.value.open();
};

const loading = ref(false);

const addForm = () => handleSubmit(false);
const editForm = () => handleSubmit(true);

const buildFormParams = (isEdit: boolean) => ({
  ...(isEdit && { id: ruleForm.id }),
  airportName: ruleForm.airportName,
  organizationId: ruleForm.organizationId,
  longitude: ruleForm.longitude,
  latitude: ruleForm.latitude,
  address: ruleForm.address,
  gatewaySn: ruleForm.gatewaySn,
  description: ruleForm.description,
  imageUrl: ruleForm.airportImage,
  ipAddress: ruleForm.ipAddress,
  gateway: ruleForm.gateway,
  videoAddress: ruleForm.videoAddress,
  windSpeedThreshold: ruleForm.windSpeedThreshold,
  rainfallThreshold: ruleForm.rainfallThreshold,
  // droneList: ruleForm.droneList,
  droneIds: ruleForm.droneIds,
});

const handleApiResponse = (isEdit: boolean) => {
  ElMessage.success(isEdit ? "修改成功" : "添加成功");
  handleBack();
};

const submitForm = async (isEdit = false) => {
  if (loading.value) return;

  try {
    loading.value = true;
    await ruleFormRef.value?.validate();

    const params = buildFormParams(isEdit);
    const { code, msg } = isEdit ? await edit(params) : await add(params);

    if (code == 200) handleApiResponse(isEdit);
    else ElMessage.error("操作失败," + msg);
  } catch (error) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};
// 地图demo
const showMap = () => {
  if (!ruleForm.address) {
    ElMessage.warning("请输入机场位置");
    return;
  }
  defaultPoint.value = [ruleForm.longitude, ruleForm.latitude];
  mapConfig.defaultPoint = defaultPoint.value;
  mapConfig.defaultAddress = ruleForm.address;
  amapVisible.value = true;
};

const getPosition = (infoObj) => {
  amapVisible.value = false;
  if (infoObj.address) {
    ruleForm.longitude = infoObj.point[0];
    ruleForm.latitude = infoObj.point[1];
    ruleForm.address = infoObj.address;
  }
};

const multipleSelect = (val) => {
  selectList.value = val;
  ruleForm.droneList = val;
  ruleForm.droneIds = val.map((item) => item.id);
};

const uvaDetail = (row) => {
  // 跳转无人机详情
  router.push({
    name: "UvaDetail",
    query: {
      id: row.id,
    },
  });
};

const delItem = (row) => {
  const index = selectList.value.findIndex((item) => item.id === row.id);
  selectList.value.splice(index, 1);
  ruleForm.droneList = selectList.value;
  ruleForm.droneIds = selectList.value.map((item) => item.id);
};

const getTableData = async () => {
  const { data } = await getOrganizationsByUserId();
  treeData.value = data;
};

const resetForm = (formEl) => {
  if (!formEl) return;
  ruleFormRef.value.resetFields();
  selectList.value = [];
};

onMounted(() => {
  getTableData();
  if (title.value == "添加机场") {
    isVisible.value = false;
  }
});
</script>

<template>
  <div class="detailPage mg-10 pd-20">
    <div class="backBtn">
      <Back width="18px" hight="18px" />
      <ElButton class="btn" @click="handleBack()">返回</ElButton>
    </div>
    <ElTabs v-model="activeName">
      <ElTabPane :label="title" name="first">
        <div class="page">
          <ElForm
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
          >
            <p class="title">归属</p>
            <ElRow>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="8"
                :xl="8"
                class="searchCol"
              >
                <ElFormItem label="所属组织：" prop="organizationId">
                  <ElTreeSelect
                    v-model="ruleForm.organizationId"
                    :data="treeData"
                    node-key="id"
                    :props="defaultProps"
                    :render-after-expand="false"
                    check-strictly
                    placeholder="请选择所属组织"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <div class="info">
              <p class="title">基本信息</p>
              <ElRow>
                <ElCol
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  class="searchCol"
                >
                  <ElFormItem label="机场名称：" prop="airportName">
                    <ElInput
                      v-model="ruleForm.airportName"
                      placeholder="请输入机场名称"
                      @input="(value) => spaceInput('airportName', value)"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  class="searchCol"
                >
                  <ElFormItem label="机场位置：" prop="address">
                    <div style="display: flex">
                      <!-- <ElInput v-model="ruleForm.longitude" placeholder="请输入经度(-180~180)"
                        style="width: 170px; margin-right: 10px">
                      </ElInput>
                      <ElInput v-model="ruleForm.latitude" placeholder="请输入纬度(-90~90)"
                        style="width: 170px; margin-right: 10px">
                      </ElInput> -->
                      <ElInput
                        v-model="ruleForm.address"
                        placeholder="请输入机场位置"
                        @input="(value) => spaceInput('address', value)"
                      >
                      </ElInput>
                      <ElButton
                        link
                        type="primary"
                        size="small"
                        @click="showMap"
                        :disabled="isVisible"
                        style="
                          padding: 0;
                          margin-top: 4px;
                          margin-left: 4px;
                          font-size: 14px;
                        "
                      >
                        <ElIcon>
                          <Location />
                        </ElIcon>
                        选择位置
                      </ElButton>
                    </div>
                  </ElFormItem>
                </ElCol>
                <ElCol
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  class="searchCol"
                >
                  <ElFormItem label="机场图片：" prop="airportImage">
                    <Upload
                      v-model:imgUrl="ruleForm.airportImage"
                      :isShowTip="isShowTip"
                      :disabled="disabled"
                      :accept="acceptImg"
                      @updateImg="updateImg"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  class="searchCol"
                >
                  <ElFormItem label="机场编号：" prop="gatewaySn">
                    <ElInput
                      v-model="ruleForm.gatewaySn"
                      placeholder="请输入机场编号"
                      @input="(value) => spaceInput('gatewaySn', value)"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  class="searchCol"
                >
                  <ElFormItem label="机场描述：" prop="description">
                    <ElInput
                      v-model="ruleForm.description"
                      placeholder="请输入机场描述"
                      type="textarea"
                      @input="(value) => spaceInput('description', value)"
                    />
                  </ElFormItem>
                </ElCol>
              </ElRow>
            </div>

            <p class="title">网络配置</p>
            <ElRow>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="IP地址：" prop="ipAddress">
                  <ElInput
                    v-model="ruleForm.ipAddress"
                    placeholder="请输入IP地址"
                    @input="(value) => spaceInput('ipAddress', value)"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="网关：" prop="gateway">
                  <ElInput
                    v-model="ruleForm.gateway"
                    placeholder="请输入网关"
                    @input="(value) => spaceInput('gateway', value)"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <p class="title">视频配置</p>
            <ElRow>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="视频地址：" prop="videoAddress">
                  <ElInput
                    v-model="ruleForm.videoAddress"
                    placeholder="请输入视频地址"
                    @input="(value) => spaceInput('videoAddress', value)"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <p class="title">环境阈值</p>
            <ElRow>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="风速阈值：" prop="windSpeedThreshold">
                  <ElInput
                    v-model="ruleForm.windSpeedThreshold"
                    placeholder="请输入风速阈值，风速超过阈值禁止无人机起飞"
                    style="margin-right: 6px"
                    @input="(value) => spaceInput('windSpeedThreshold', value)"
                  >
                  </ElInput>
                  m/s
                </ElFormItem>
              </ElCol>
              <ElCol
                :xs="24"
                :sm="12"
                :md="12"
                :lg="12"
                :xl="12"
                class="searchCol"
              >
                <ElFormItem label="降雨阈值：" prop="rainfallThreshold">
                  <ElInput
                    v-model="ruleForm.rainfallThreshold"
                    placeholder="请输入降雨阈值，降雨量超过阈值禁止无人机起飞"
                    style="margin-right: 6px"
                    @input="(value) => spaceInput('rainfallThreshold', value)"
                  >
                  </ElInput>
                  mm
                </ElFormItem>
              </ElCol>
            </ElRow>
            <p class="title">配置无人机</p>
            <div class="flex" v-if="selectList.length == 0">
              <ElButton class="bind" @click="bindAddUAV">绑定无人机</ElButton>
            </div>
            <div v-if="selectList.length > 0" style="margin-top: 30px">
              <ElTable :data="selectList" style="width: 100%" stripe>
                <ElTable.TableColumn
                  prop="droneName"
                  label="无人机名称"
                  align="center"
                />
                <ElTable.TableColumn
                  prop="droneBrand"
                  label="无人机品牌"
                  align="center"
                />
                <ElTable.TableColumn
                  prop="droneModel"
                  label="无人机型号"
                  align="center"
                />
                <ElTable.TableColumn fixed="right" label="操作" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="uvaDetail(scope.row)"
                    >
                      详情
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="delItem(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </ElTable.TableColumn>
              </ElTable>
            </div>
            <ElDivider />
            <ElFormItem>
              <div class="buts">
                <ElButton @click="resetForm(ruleFormRef)">清空</ElButton>
                <ElButton
                  type="primary"
                  @click="() => submitForm(title !== '添加机场')"
                  :loading="loading"
                >
                  确定
                </ElButton>
              </div>
            </ElFormItem>
          </ElForm>
        </div>
      </ElTabPane>
    </ElTabs>
    <airportList ref="selectAirport" @multipleSelect="multipleSelect" />
    <GaoAmap
      :isShow="amapVisible"
      :data="mapConfig"
      :showSearch="true"
      @getPosition="getPosition"
    ></GaoAmap>
  </div>
</template>
<style scoped>
p {
  font-weight: 900;
}

.title {
  padding: 8px 10px;
  margin-bottom: 16px;
  font-size: 14px;
  background: #f5f7fa;
}

.bold {
  font-weight: 500;
}

.flex {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  width: 100%;
}

.bind {
  color: var(--el-color-primary);
  border: 1px solid var(--el-color-primary);
}

.buts {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.el-input,
.el-textarea {
  width: 350px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.logo-uploader {
  display: block;
  width: 148px;
  height: 148px;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>
